package cn.umbrella.crm_core.settings.interceptor;

import cn.umbrella.crm_core.commons.contants.CONTANTS_CODE;
import cn.umbrella.crm_core.settings.domain.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
	    throws Exception {
	// 获取当前session的用户
	HttpSession session = request.getSession();
	User currentUser = (User) session.getAttribute(CONTANTS_CODE.SESSION_USER);
	// 如果当前session中用户存在，证明用户已经登录成功，否则，重定向至登录页面
	if (currentUser == null) {
	    // 重定向至登录页面
	    response.sendRedirect(request.getContextPath());
	    return false;
	}
	return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
	    ModelAndView modelAndView) throws Exception {
	// TODO Auto-generated method stub
	HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
	    throws Exception {
	// TODO Auto-generated method stub
	HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
